//
//  LoginViewController.swift
//  WangPu
//
//  Created by xiaozhi on 15/9/24.
//  Copyright (c) 2015年 zhixiao. All rights reserved.
//

import UIKit

class LoginViewController: BaseViewController {
    var bgImageView:UIImageView!
    var loginBgView:UIView!
    var userName:MyTextField!
    var passward:MyTextField!
    var currentTextField:UITextField?
    var loginBtn:UIButton!
    var forgetBtn:UIButton!
    var regsiterBtn:UIButton!
    var unnameLoginBtn:UIButton!
    var showPwd:Bool = false
    var loginSuccess:((userInfo:NSDictionary?)->Void)?
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "登录旺铺"
        let backItem = UIBarButtonItem(image: UIImage(named: "back_icon"), style:UIBarButtonItemStyle.Plain, target:self, action:"goBack")
        backItem.tintColor = UIColor.whiteColor()
        self.navigationItem.leftBarButtonItem = backItem
        self.automaticallyAdjustsScrollViewInsets = false
        self.view.backgroundColor = UIColor.whiteColor()
        self.createTopView()
        self.createLoginInfo()
        self.createButtons()
        // Do any additional setup after loading the view.
    }
    override func viewWillAppear(animated: Bool){
        super.viewWillAppear(animated)
        navigationController?.navigationBarHidden = false
    }
    func  goBack(){
        self.navigationController?.popViewControllerAnimated(true)
    }
    func createTopView()->Void{
        let imageRatio:CGFloat = 0.5

        let imageview = UIImageView(frame: CGRectMake(0, 20, view.bounds.size.width, view.bounds.size.width*imageRatio))
        imageview.backgroundColor = commonBackgoundColor
        imageview.userInteractionEnabled = true
        view.addSubview(imageview)
        
        let logoImage = UIImageView(frame: CGRectMake((view.bounds.size.width-141)/2.0, imageview.bounds.size.height - 77, 141, 52))
        logoImage.image = UIImage(named: "login-logo")
        imageview.addSubview(logoImage)
        bgImageView = imageview

    }
    func createLoginInfo()->Void{
        let bgView = UIView(frame: CGRectMake(10, CGRectGetMaxY(bgImageView.frame)+20, view.bounds.size.width-20, 100))
        bgView.layer.borderColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.1).CGColor
        bgView.layer.borderWidth = onePix
        bgView.layer.cornerRadius = 6.0
        view.addSubview(bgView)
        loginBgView = bgView
        userName = MyTextField(frame: CGRectMake(0,0, bgView.bounds.size.width, bgView.bounds.size.height/2.0))
        userName.borderStyle = UITextBorderStyle.None
        userName.placeholder = "用户名"
//        userName.text = "18217263157"
        userName.font = UIFont.systemFontOfSize(14)
        userName.delegate = self
        let leftView1 = UIImageView(frame: CGRectMake(10, 0, 15, 18))
        leftView1.image = UIImage(named: "user")
        userName.leftView = leftView1
        userName.leftViewMode = UITextFieldViewMode.Always
        bgView.addSubview(userName)
        
        let line = UIView(frame: CGRectMake(10, CGRectGetMaxY(userName.frame), bgView.bounds.size.width-20, onePix))
        line.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.1)
        bgView.addSubview(line)
        
        passward = MyTextField(frame: CGRectMake(0,bgView.bounds.size.height/2.0+1, bgView.bounds.size.width, bgView.bounds.size.height/2.0-1))
        passward.borderStyle = UITextBorderStyle.None
        passward.placeholder = "密码"
        passward.secureTextEntry = true
        passward.font = UIFont.systemFontOfSize(14)
        passward.delegate = self
//        passward.text = "123456"
        let leftView2 = UIImageView(frame: CGRectMake(10, 0, 16, 16))
        leftView2.image = UIImage(named: "password")
        passward.leftView = leftView2
        passward.leftViewMode = UITextFieldViewMode.Always
        
        let rightView = UIView(frame: CGRectMake(0, 0, 70, 30))
        let clearBtn = UIButton(frame: CGRectMake(0, 0, 30, 30))
        clearBtn.setImage(UIImage(named: "center_close"), forState: UIControlState.Normal)
        clearBtn.addTarget(self, action: "clearpwd", forControlEvents: UIControlEvents.TouchUpInside)
        rightView.addSubview(clearBtn)
        
        let showPwdBtn = UIButton(frame: CGRectMake(30, 0, 30, 30))
        showPwdBtn.setImage(UIImage(named: "center_dark"), forState: UIControlState.Normal)
        showPwdBtn.addTarget(self, action: "showPwd:", forControlEvents: UIControlEvents.TouchUpInside)
        rightView.addSubview(showPwdBtn)
        
        passward.rightView = rightView
        passward.rightViewMode = UITextFieldViewMode.WhileEditing
        bgView.addSubview(passward)
    }
    func showPwd(button:UIButton)->Void{
        self.showPwd = !self.showPwd
        if self.showPwd{
            button.setImage(UIImage(named: "eye"), forState: UIControlState.Normal)

        }
        else{
            button.setImage(UIImage(named: "center_dark"), forState: UIControlState.Normal)
        }
        let text = self.passward.text!.copy()
        self.passward.text = nil
        self.passward.secureTextEntry = !self.showPwd
        self.passward.text = text as? String
    }
    func clearpwd(){
        self.passward.text = nil
    }
    func createButtons(){
        //登录
        loginBtn = UIButton(frame: CGRectMake(10, CGRectGetMaxY(loginBgView.frame)+20, view.bounds.size.width-20, 40))
        loginBtn.setTitle("登录", forState: UIControlState.Normal)
        loginBtn.titleLabel?.font = UIFont.boldSystemFontOfSize(14)
        loginBtn.backgroundColor = commonRedColor
        loginBtn.layer.cornerRadius = 5.0
        loginBtn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        loginBtn.addTarget(self, action: "loginClick", forControlEvents: UIControlEvents.TouchUpInside)
        view.addSubview(loginBtn)
        //忘记密码
        forgetBtn = UIButton(frame: CGRectMake(5, CGRectGetMaxY(loginBtn.frame)+5, 70, 30))
        forgetBtn.setTitle("忘记密码?", forState: UIControlState.Normal)
        forgetBtn.titleLabel?.font = UIFont.systemFontOfSize(14)
        forgetBtn.setTitleColor(commonRedColor, forState: UIControlState.Normal)
        forgetBtn.addTarget(self, action: "forgetClick", forControlEvents: UIControlEvents.TouchUpInside)
        view.addSubview(forgetBtn)
        //注册
        regsiterBtn = UIButton(frame: CGRectMake(view.bounds.size.width-50, CGRectGetMaxY(loginBtn.frame)+5, 50, 30))
        regsiterBtn.setTitle("注册", forState: UIControlState.Normal)
        regsiterBtn.titleLabel?.font = UIFont.systemFontOfSize(14)
        regsiterBtn.setTitleColor(commonRedColor, forState: UIControlState.Normal)
        regsiterBtn.addTarget(self, action: "regsisterClick", forControlEvents: UIControlEvents.TouchUpInside)
        view.addSubview(regsiterBtn)
//        //匿名登录
//        unnameLoginBtn = UIButton(frame: CGRectMake(view.bounds.size.width/2.0-40, CGRectGetMaxY(regsiterBtn.frame)+30, 80, 30))
//        unnameLoginBtn.setTitle("匿名登录", forState: UIControlState.Normal)
//        unnameLoginBtn.titleLabel?.font = UIFont.systemFontOfSize(14)
//        unnameLoginBtn.layer.borderWidth = 1.0
//        unnameLoginBtn.layer.borderColor = commonRedColor.CGColor
//        unnameLoginBtn.layer.cornerRadius = 5.0
//        unnameLoginBtn.setTitleColor(commonRedColor, forState: UIControlState.Normal)
//        unnameLoginBtn.addTarget(self, action: "unNameClick", forControlEvents: UIControlEvents.TouchUpInside)
//        view.addSubview(unnameLoginBtn)
//        //快速登录
//        let noteLabel = UILabel(frame: CGRectMake((view.bounds.size.width-90)/2.0, CGRectGetMaxY(unnameLoginBtn.frame)+30, 90, 30))
//        noteLabel.text = "快速登录"
//        noteLabel.textColor = UIColor.lightGrayColor()
//        noteLabel.textAlignment = NSTextAlignment.Center
//        noteLabel.font = UIFont.systemFontOfSize(15)
//        view.addSubview(noteLabel)
//        let line1 = UIView(frame: CGRectMake(15, CGRectGetMidY(noteLabel.frame), view.bounds.size.width/2-noteLabel.frame.size.width/2.0-15, 1))
//        line1.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.1)
//        view.addSubview(line1)
//        let line2 = UIView(frame: CGRectMake(view.bounds.size.width/2+noteLabel.frame.size.width/2.0,  CGRectGetMidY(noteLabel.frame), view.bounds.size.width/2-noteLabel.frame.size.width/2.0-15, 1))
//        line2.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.1)
//        view.addSubview(line2)
//        //新浪
//        let sinaLoginBtn = TabButton(frame: CGRectMake(view.bounds.size.width/2.0-40, CGRectGetMaxY(noteLabel.frame)+10, 80, 80))
//        sinaLoginBtn.alwaysUnhightlighted = false
//        sinaLoginBtn.setTitle("微博登录", forState: UIControlState.Normal)
//        sinaLoginBtn.titleLabel?.font = UIFont.boldSystemFontOfSize(14)
//        sinaLoginBtn.titleLabel?.textAlignment = NSTextAlignment.Center
//        sinaLoginBtn.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)
//        sinaLoginBtn.setImage(UIImage(named:"TabBar1"), forState: UIControlState.Normal)
//        sinaLoginBtn.imageView?.contentMode = UIViewContentMode.ScaleAspectFit
//        view.addSubview(sinaLoginBtn)
//        //微信
//        let wxLoginBtn = TabButton(frame: CGRectMake(20, CGRectGetMaxY(noteLabel.frame)+10, 80, 80))
//        wxLoginBtn.alwaysUnhightlighted = false
//        wxLoginBtn.setTitle("微信登录", forState: UIControlState.Normal)
//        wxLoginBtn.titleLabel?.font = UIFont.boldSystemFontOfSize(14)
//        wxLoginBtn.titleLabel?.textAlignment = NSTextAlignment.Center
//        wxLoginBtn.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)
//        wxLoginBtn.setImage(UIImage(named:"TabBar1"), forState: UIControlState.Normal)
//        wxLoginBtn.imageView?.contentMode = UIViewContentMode.ScaleAspectFit
//        view.addSubview(wxLoginBtn)
//        //QQ
//        let QQLoginBtn = TabButton(frame: CGRectMake(view.bounds.size.width-80-20, CGRectGetMaxY(noteLabel.frame)+10, 80, 80))
//        QQLoginBtn.alwaysUnhightlighted = false
//        QQLoginBtn.setTitle("QQ登录", forState: UIControlState.Normal)
//        QQLoginBtn.titleLabel?.font = UIFont.boldSystemFontOfSize(14)
//        QQLoginBtn.titleLabel?.textAlignment = NSTextAlignment.Center
//        QQLoginBtn.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)
//        QQLoginBtn.setImage(UIImage(named:"TabBar1"), forState: UIControlState.Normal)
//        QQLoginBtn.imageView?.contentMode = UIViewContentMode.ScaleAspectFit
//        view.addSubview(QQLoginBtn)
    }
    func startLogin(name:String?,pwd:String?)->Void{

        if let name = self.userName.text{
            let nameinfo = name.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) as NSString
            if nameinfo.length == 0{
                self.showTips("用户名不能为空")
                return
            }
        }
        else{
            self.showTips("用户名不能为空")
            return
        }

        if let pwd = self.passward.text{
            let pwdInfo = pwd.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) as NSString
            if pwdInfo.length == 0{
                self.showTips("密码不能为空")
                return
            }
        }
        else{
            self.showTips("密码不能为空")
            return
        }
        let request = NetWorkHelper()
        let parameters = NSMutableDictionary()
        parameters.setObject(self.userName.text!, forKey:"name")
        parameters.setObject(self.passward.text!, forKey: "password")
        request.requestStart("/account/login", parameters: parameters,compeleteHandle:{ (data, response, error)  in
            dispatch_async(dispatch_get_main_queue()){
                self.hiddenProcessView()
            }
            if error == nil{
                var dic:NSDictionary?
                do {
                    dic = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
                } catch let error as NSError {
                    print(error)
                    dispatch_async(dispatch_get_main_queue()){
                        self.showTips("服务器数据异常")
                    }
                    return
                }
                if (dic?["result"])! as! String == "0"{
                    dispatch_async(dispatch_get_main_queue()){
                        if let session = dic?["data"]?["session"] as? String{
                            GlobalDataHelper.instance.session = session
                            self.getUserInfo()
                            
                        }
                    }
                }
                else{
                    dispatch_async(dispatch_get_main_queue(), {[weak self] in
                        self?.showTips(dic?["msg"] as? String)
                        })
                    
                }
            }
        })
        self.showProcess("登录中...")
    }
    func getUserInfo()->Void{
        let request = NetWorkHelper()
        let parameters = NSMutableDictionary()
        parameters.setObject(GlobalDataHelper.instance.session!, forKey: "frontend")
        request.requestStart("/user/baseinfo", parameters: parameters,compeleteHandle:{ (data, response, error)  in
            dispatch_async(dispatch_get_main_queue()){
                self.hiddenProcessView()
            }
            if error == nil{
                var dic:NSDictionary?
                do {
                    dic = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
                } catch let error as NSError {
                    print(error)
                    dispatch_async(dispatch_get_main_queue()){
                        self.showTips("服务器数据异常")
                    }
                    return
                }
                if (dic?["result"])! as! String == "0"{
                    dispatch_async(dispatch_get_main_queue()){
                        self.showTips("加载成功"){
                            self.loginSuccess?(userInfo: dic?["data"] as? NSDictionary)
                            self.navigationController?.popViewControllerAnimated(true)
                        }
                    }
                }
                else{
                    dispatch_async(dispatch_get_main_queue(), {[weak self] in
                        self?.showTips(dic?["msg"] as? String)
                        })
                    
                }
            }
        })
        self.showProcess("正在加载用户数据...")
    }
    func  loginClick(){
//        let ctl = LoginViewController()
//        self.navigationController?.pushViewController(ctl, animated: true)
        self.startLogin("", pwd: "")
    }
    func  forgetClick(){
        let ctl = RegisterViewController()
        ctl.type = ActionType.ForgetPassword
        navigationController?.pushViewController(ctl, animated: true)
    }
    func  regsisterClick(){
        let ctl = RegisterViewController()
        ctl.type = ActionType.Register
        navigationController?.pushViewController(ctl, animated: true)
    }
    func  unNameClick(){
        //        self.navigationController?.popViewControllerAnimated(true)
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    deinit{
        print("login ctl deinit")
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
extension LoginViewController:UITextFieldDelegate{
    func textFieldDidBeginEditing(textField: UITextField){
        self.currentTextField = textField
    }
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        self.currentTextField?.resignFirstResponder()
        return true
    }
}